package cn.wolfcode.rbac.web.intercptor;

import cn.wolfcode.rbac.domain.Employee;
import cn.wolfcode.rbac.util.RequiredPermission;
import cn.wolfcode.rbac.util.UserContext;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.List;

public class SecurityInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        //0 获取当前用户
        Employee current = UserContext.getCurrent();
        //1 判断是否是超管
        if(current.isAdmin()){
            return true;
        }
        //2 判断方法上是否有该注解如果没有直接放行
        HandlerMethod handlerMethod = (HandlerMethod)handler;
        Method method = handlerMethod.getMethod();
        RequiredPermission annotation = method.getAnnotation(RequiredPermission.class);
        if(annotation == null){
            return true;
        }
        //3 如果有看是否在该用户所拥有的权限集合中
        List<String> expressions = UserContext.getExpressions();
        if(expressions.contains(annotation.value()[1])){
            return true;
        }
        //4 如果不在跳转到没有权限的界面
        request.getRequestDispatcher("/WEB-INF/views/common/nopermission.jsp").forward(request,response);
        return false;
    }

}
